package chapter15;

import java.util.ArrayList;
import java.util.List;

public class PrettyPrinting {


    /**
     * 整齐打印
     */
    public static List<String> prettyPrinting(String[] x, int M) {
        List<String> table = new ArrayList<>();
        StringBuilder row = new StringBuilder();

        int n = x.length;
        int i = 0;
        int j = 0;
        while (i <= j && j < n) {

            int l = 0;
            for (int k = i; k <= j; k++) {
                l += x[k].length();
            }
            if (M - j + i - l < 0) {
                if (row.length() < M) {
                    row.append("_".repeat(Math.max(0, M - row.length())));
                }
                table.add(row.toString());
                row = new StringBuilder();

                i = j;
                continue;
            }

            row.append(x[j]);
            if (row.length() < M) {
                row.append("_");
            }

            j++;
        }
        table.add(row.deleteCharAt(row.length() - 1).toString());
        return table;
    }

    public static void printPrettyPrinting(String[] x, int M) {
        List<String> table = prettyPrinting(x, M);
        table.forEach(System.out::println);
    }

}
